package org.example.scheduled;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.ShoppingCart;
import org.example.mapper.ShoppingCartMapper;
import org.example.service.ShoppingCartService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class CopyScheduled {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Scheduled(cron="0 1 18 * * ?")
    public void copy() {
        log.info("开始备份");
        //清空数据
        shoppingCartMapper.clearShoppingCart();
        HashOperations<String, Object, Object> ops = stringRedisTemplate.opsForHash();
        //所有的购物车key
        Set<String> keys = stringRedisTemplate.keys("gwc*");
        log.info("keys:{}",keys);
        //通过循环向数据库中存放数据
        keys.forEach(key -> {
            //String userId = key.substring(4);
            String userId = key.replace("gwc", "");
            Map<Object, Object> entries = ops.entries(key);
            entries.keySet().forEach(bookId->{
                int number = Integer.parseInt(entries.get(bookId).toString());
                ShoppingCart sc = new ShoppingCart();
                sc.setId(bookId.toString());
                sc.setUserId(userId);
                sc.setNumber(number);
                shoppingCartService.save(sc);
                //清除redis中的数据
                //ops.delete(key,bookId)
            });
        });
    }
}
